package com.wceManage.manage.util.wxPay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wceManage.commons.util.ConfigPropKit;
import com.wceManage.commons.util.TimeUtil;
import com.wceManage.manage.util.EscapeUtil;

/**
 * 微信工具类
 * 
 * @author huangheng
 * @date 20190513
 *
 */
public class WeixinUtil {
	// 全局常量
	public static String accesstoken = "";
	private static String jsapi_ticket = "";
	private static long timestamp = 1460602940;
	private static long timestampatk = 1460602940;

	// 获取微信配置信息
	public static Map<String, String> getSign(String url) {

		Map<String, String> jsonMap = new HashMap<String, String>();
		try {
			// 获取与当前时间戳之间的分钟数
			long now = TimeUtil.getUnixTimestamp();// 当前时间戳
			String j = "1";
			String s = "2";

			// 获取access_token
			String access_token = accesstoken;
			if ((now - timestampatk) > 7000 || "".equals(accesstoken) || accesstoken == null) {

				s = weChatSendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="
						+ ConfigPropKit.get("wx_appid") + "&secret=" + ConfigPropKit.get("wx_secret"));
				JSONObject a = JSON.parseObject(s);
				access_token = a.getString("access_token");
				accesstoken = access_token;
				timestampatk = now;
			}
			// jsapi_ticket
			if ((now - timestamp) > 7000 || "".equals(jsapi_ticket) || jsapi_ticket == null) {
				// 获取jsapi_ticket
				j = weChatSendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket",
						"access_token=" + access_token + "&type=jsapi");
				JSONObject b = JSON.parseObject(j);

				String ticket = b.getString("ticket");
				timestamp = now;
				jsapi_ticket = ticket;
			}
			// 生成JS-SDK权限验证的签名
			jsonMap = sign(jsapi_ticket, url);

			jsonMap.put("secret", ConfigPropKit.get("wx_secret"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonMap;
	}

	/***************************************** 微信签名算法 *********************************************************/
	private static Map<String, String> sign(String jsapi_ticket, String url) {
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";

		// 注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		ret.put("appId", ConfigPropKit.get("wx_appid"));
		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);

		return ret;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	// 微信
	public static String weChatSendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			System.out.println("url=" + urlNameString);
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return EscapeUtil.unescape(result);
	}

	public static String createSign(Map<String, String> param, String key) {
		List<String> pnamelist = new ArrayList<String>();
		Iterator<String> keys = param.keySet().iterator();
		while (keys.hasNext()) {
			pnamelist.add(keys.next());
		}
		String[] pnames = pnamelist.toArray(new String[0]);
		Arrays.sort(pnames);
		StringBuilder keyvalue = new StringBuilder();
		for (String item : pnames) {
			String vl = param.get(item) == null ? "" : param.get(item);
			if (keyvalue.length() > 0)
				keyvalue.append("&");
			keyvalue.append(item + "=" + vl);
		}
		keyvalue.append("&key=" + key);
		return getMD5(keyvalue.toString()).toLowerCase();
	}

	/**
	 * 获取MD5
	 */
	@SuppressWarnings("static-access")
	public static String getMD5(String s) {
		GenerateMD5 generateMD5 = new GenerateMD5();
		generateMD5.getMD5().update(s.getBytes());
		byte digest[] = generateMD5.getMD5().digest();
		StringBuilder builder = new StringBuilder();
		for (byte b : digest) {
			builder.append(String.format("%02X", b));
		}
		return builder.toString().toLowerCase();
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, Map<String, ?> paramMap) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";

		String param = "";
		Iterator<String> it = paramMap.keySet().iterator();

		while (it.hasNext()) {
			String key = it.next();
			param += key + "=" + paramMap.get(key) + "&";
		}

		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

}
